package base.网络编程.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class course1 {
    public static void main(String[] args) throws IOException {
        Datagram t1 = new Datagram();
        t1.start();

        /*接收数据*/
        ServerSocket server = new ServerSocket(10000);
        Socket socket = server.accept();//监听客户端接

        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        int s;
        while ((s = isr.read()) != -1){
            System.out.print((char) s);
        }

        is.close();
        socket.close();
        server.close();
    }
}
class Datagram extends Thread{
    @Override
    public void run() {
        /*TCP协议
         * 基于IO流传输数据
         * :需要释放资源
         * */

        try {
            Thread.sleep(1000);

            Socket socket = new Socket("127.0.0.1",10000);
            OutputStream os = socket.getOutputStream();
            os.write("你好世界！".getBytes());

            os.close();
            socket.close();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}